
/*
 * Copyright (C) 2020 Yumin Wu <wuyuminst@163.com>
 *
 * This software is available to you under a choice of one of two
 * licenses.  You may choose to be licensed under the terms of the GNU
 * General Public License (GPL), available from the file
 * COPYING in the main directory of this source tree, or the
 * OpenIB.org BSD license below:
 *
 *     Redistribution and use in source and binary forms, with or
 *     without modification, are permitted provided that the following
 *     conditions are met:
 *
 *      - Redistributions of source code must retain the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer.
 *
 *      - Redistributions in binary form must reproduce the above
 *        copyright notice, this list of conditions and the following
 *        disclaimer in the documentation and/or other materials
 *        provided with the distribution.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "encode_control.h"
#include <sys/time.h>

char *g_path = "/oem";

int enc_ctl_init(struct enc_ctl *e, int w, int h)
{
	if (e->size)
        return 0;
	
	if (rga_control_buffer_init(&e->enc_bo, &e->enc_fd, w, h, 12))
        return -1;
    e->size = w * h * 3 / 2;

    return 0;
}

void enc_ctl_exit(struct enc_ctl *e)
{
	if(e->size) {
		rga_control_buffer_deinit(&e->enc_bo, e->enc_fd);
	}
}

int enc_ctl_run(struct enc_ctl *e, int src_fd, void *src_buf, int width, int height, 
						RgaSURF_FORMAT fmt, int rotation)
{
	FILE *fp;
	
	if (enc_ctl_init(e, width, height))
        return -1;
	if (width * height * 3 / 2 > e->size)
        return -1;
	gettimeofday(&e->t0, NULL);
	snprintf(e->name, sizeof(e->name), "%s/%ld.%06ld.jpg",
                    g_path, e->t0.tv_sec, e->t0.tv_usec);
	
	/* set the quanlity: 0~10 */
	if (vpu_encode_jpeg_init(&e->enc, width, height, 10, MPP_FMT_YUV420SP))
        return -1;

	vpu_encode_jpeg_doing(&e->enc, src_buf, src_fd, width * height * 3 / 2,
	        e->enc_bo.ptr, e->enc_fd, e->size);
	fp = fopen(e->name, "wb");
	if(fp) {
		fwrite(e->enc.enc_out_data, 1, e->enc.enc_out_length, fp);
        fclose(fp);
        printf("%s: save %s ok!\n", __func__, e->name);
	} else {
		printf("%s: open %s fail!\n", __func__, e->name);
	}

	vpu_encode_jpeg_done(&e->enc);
    return 0;
}


